package com.gxl.butt.interceptor;

import com.gxl.butt.redis.RedisUtil;
import com.gxl.butt.utils.AddressUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by guoxiaolin on 2018/12/14.
 */
public class BadIpInterceptor  extends HandlerInterceptorAdapter {

    private Logger logger = LoggerFactory.getLogger(BadIpInterceptor.class);

    @Autowired
    private RedisUtil redisUtil;

    /**
     * 在DispatcherServlet之前执行
     * */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String ipAddr = AddressUtil.getIpAddr(request);
        Long l = System.currentTimeMillis() / 1000;
        String key = "BADIP:" + ipAddr + l.toString();
        String ipset = "BADIP:setHMD";
        synchronized (BadIpInterceptor.class) {
            Boolean heimiandan = redisUtil.sHasKey(ipset, ipAddr);
            if (heimiandan) {
                logger.info(ipAddr + " 地址访问异常,已拦截");
                return false;
            }
            Object visitTimeObj = redisUtil.get(key);
            if (visitTimeObj != null && !"".equals(visitTimeObj)) {
                Integer iPvalue = (Integer) visitTimeObj;
                redisUtil.incr(key,1L);
                logger.info(ipAddr + " 进行了第 " + iPvalue + " 次访问");
                if (iPvalue >= 300) {
                    redisUtil.sSet(ipset, ipAddr);
                    redisUtil.expire(ipset,  1L * 60L * 60L);
                    logger.info(ipAddr + " 非正常访问，添加ip限制");
                    return false;
                }
                logger.info(ipAddr + " 正常访问，不进行拦截");
            } else {
                redisUtil.set(key, 1,  5L);
            }
        }
        return true;
    }


    /**
     * 在controller执行之后的DispatcherServlet之后执行
     * */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

        System.out.println("===========HandlerInterceptor98 postHandle");

    }

    /**
     * 在页面渲染完成返回给客户端之前执行
     * */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

        System.out.println("===========HandlerInterceptor98 afterCompletion");

    }
}
